package net.hn.hnms.biz.shipped.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.hn.hnms.biz.api.plan.model.RailroadLoadingDto;
import net.hn.hnms.biz.shipped.domain.RailroadLoadingPo;
import net.hn.hnms.biz.shipped.domain.RailwayLoadMonthData;
import net.hn.hnms.biz.shipped.domain.RailwayLoadYearData;
import net.hn.hnms.biz.shipped.domain.Vo.RailroadLoadingVo;
import net.hn.hnms.biz.shipped.mapper.RailroadLoadingMapper;
import net.hn.hnms.biz.shipped.service.RailroadLoadService;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

@Service
@DS("master")
public class RailroadLoadServiceImpl implements RailroadLoadService {
    @Resource
    private RailroadLoadingMapper railroadLoadingMapper;

    /**
     * 获取年总重和上月数据
     * @param mineCode
     * @return
     */
    @Override
    public RailroadLoadingVo yearRealWeightAndlastMonthSum(String mineCode) {
        RailroadLoadingVo railroadLoadingVo = new RailroadLoadingVo();
        //获取最新的一条数据
        RailroadLoadingPo railroadLoadingPo=railroadLoadingMapper.selectOneRailroadLoadingByData(mineCode);
        if (railroadLoadingPo == null) {
            return railroadLoadingVo;
        }
        railroadLoadingVo.setYearTime(railroadLoadingPo.getYearTime());
        railroadLoadingVo.setYearRealWeight(railroadLoadingPo.getYearRealWeight());

        railroadLoadingVo.setLastMonthTime(railroadLoadingPo.getLastMonthTime());
        railroadLoadingVo.setLastMonthSum(railroadLoadingPo.getLastMonthSum());
        railroadLoadingVo.setDataTime(railroadLoadingPo.getDataTime());
        return railroadLoadingVo;
    }

    /**
     * 保存铁路装车年月数据
     * @param railroadLoadingDto
     * @return
     */
    @Override
    public Boolean saveRailroadload(RailroadLoadingDto railroadLoadingDto) {
        RailroadLoadingPo railroadLoadingPo = new RailroadLoadingPo();
//        railroadLoadingPo.setDataTime(railroadLoadingDto.getDataTime());
//        railroadLoadingPo.setYearTime(railroadLoadingDto.getYearTime());
//        railroadLoadingPo.setYearRealWeight(railroadLoadingDto.getYearRealWeight());
//        railroadLoadingPo.setLastMonthTime(railroadLoadingDto.getLastMonthTime());
//        railroadLoadingPo.setLastMonthSum(railroadLoadingDto.getLastMonthSum());
        String IpYear = "http://10.108.90.132/open/api/1/ratilway/load/daily/year?pageNo=0&pageSize=20&masterKey=exEQhbVqMPLFAXbn1usA&appKey=zV5DRBy04ehSgOCBo4PV";
        String IpLastMonth = "http://10.108.90.132/open/api/1/railway/load/daily/lastmonth?pageNo=0&pageSize=20&type=-1&masterKey=exEQhbVqMPLFAXbn1usA&appKey=zV5DRBy04ehSgOCBo4PV&0=12";
        String appToken = "T3FUUEhJYzh4M1kybmxwYWZOaTQrZXhFUWhiVnFNUExGQVhibjF1c0E=";
        //获取年数据
        RailwayLoadYearData YearData = null;
        try {
//            yearDataRailwayLoadData = this.sendGetRequest(IpYear, null, new TypeReference<RailwayLoadData<RailwayLoadData.YearData>>() {});
            YearData = this.sendGetRequest(IpYear, appToken, RailwayLoadYearData.class);

        } catch (IOException e) {
            System.out.println("获取年数据异常");

            throw new RuntimeException(e);
        }
        RailwayLoadMonthData LastMonthData = null;
        try {
            LastMonthData = this.sendGetRequest(IpLastMonth, appToken, RailwayLoadMonthData.class);
        } catch (IOException e) {
            System.out.println("获取月数据异常");
            throw new RuntimeException(e);
        }
        //获取月数据

        String yearTime = "";
        String yearRealWeight = "";
        String LastMonthTime = "";
        String LastMonthsum = "";
        if (YearData != null && YearData.getContent()[0] != null) {
            //获取到了年数据
            yearTime= YearData.getContent()[0].getYeartime();
            yearRealWeight= YearData.getContent()[0].getRealweight();
        }
        if (LastMonthData != null && LastMonthData.getContent()[0] != null) {
            //获取到了月数据
            LastMonthTime=LastMonthData.getContent()[0].getMonthTime();
            LastMonthsum=LastMonthData.getContent()[0].getSum();
        }
        railroadLoadingPo.setYearTime(yearTime);
        railroadLoadingPo.setYearRealWeight(yearRealWeight);
        railroadLoadingPo.setLastMonthTime(LastMonthTime);
        railroadLoadingPo.setLastMonthSum(LastMonthsum);
        if (railroadLoadingDto.getDataTime() != null) {
            railroadLoadingPo.setDataTime(railroadLoadingDto.getDataTime());
        } else {
            railroadLoadingPo.setDataTime(new Date());
        }
        System.out.println(railroadLoadingPo.toString());
        int insert = railroadLoadingMapper.insert(railroadLoadingPo);
        if (insert > 0) {
            return true;
        }
        return false;
    }
    public   <T> T sendGetRequest(String url,String token,  TypeReference<T> responseType) throws IOException {
        // 创建URL对象
        URL apiUrl = new URL(url);

        // 打开HTTP连接
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

        // 设置请求头
//        connection.setRequestProperty("appToken", appToken);

        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + token);

        // 设置请求方法
        connection.setRequestMethod("GET");

        // 获取响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseData = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseData.append(inputLine);
            }

            // 关闭输入流
            in.close();

            // 将JSON字符串解析为对象
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(responseData.toString(), responseType);
        }
        return null;
    }
    public  <T> T sendGetRequest(String url,String appToken, Class<T> responseType) throws IOException {
        // 创建URL对象
        URL apiUrl = new URL(url);

        // 打开HTTP连接
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

        // 设置请求头
        connection.setRequestProperty("appToken", appToken);

        // 设置请求方法
        connection.setRequestMethod("GET");

        // 获取响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseData = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseData.append(inputLine);
            }

            // 关闭输入流
            in.close();

            // 将JSON字符串解析为对象
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(responseData.toString(), responseType);
        }
        return null;
    }
}
